using System;
using System.Collections;
using System.Web;
using System.Web.Caching;
using System.Collections.Generic;
using FwkLight.Application;
using FwkLight.CodeExtensions;
using StructureMap;

namespace FwkLight.Web
{
  public interface ICacheItemDictionary : IItemDictionary
  {
  }

  public class CacheItemDictionary: ICacheItemDictionary
  {
    private readonly Cache _cache = HttpRuntime.Cache;
    private readonly int _cachingTimeInHours = ApplicationConstants.Caching.DefaultCachingTimeInHours;
    private const string NULLInCache = "NULL";
    private ICacheDependencyList _cacheDependencyList = ObjectFactory.GetInstance<ICacheDependencyList>();

    public void Add<ItemToPutInContext> ( IItemKey<ItemToPutInContext> key, ItemToPutInContext item )
    {
      if (item == null)
        _cache.Insert(key.Key, NULLInCache, null, DateTime.Now.AddHours(_cachingTimeInHours),
                    Cache.NoSlidingExpiration);
      else _cache.Insert( key.Key, item, null, DateTime.Now.AddHours(_cachingTimeInHours),
                    Cache.NoSlidingExpiration );
    }

    public void Add<ItemToPutInContext>(IItemKey<ItemToPutInContext> key, ItemToPutInContext item, int cachingTimeInHours)
    {
      if (item == null)
        _cache.Insert(key.Key, NULLInCache, null, DateTime.Now.AddHours(cachingTimeInHours), Cache.NoSlidingExpiration);
      else
        _cache.Insert(key.Key, item, null, DateTime.Now.AddHours(cachingTimeInHours), Cache.NoSlidingExpiration);
    }

    public Item Get<Item> ( IItemKey<Item> key )
    {
      if (_cache[key.Key] == null)
      {
        return default(Item);
      }

      if (_cache[key.Key].ToString() == NULLInCache)
        return default(Item);

      return (Item)_cache[key.Key ];
    }

    public bool Contains<Item>(IItemKey<Item> key)
    {
      return _cache.Get(key.Key) != null;
    }

    public void Remove<ItemToPutIn>(IItemKey<ItemToPutIn> key)
    {
      _cache.Remove(key.Key);
    }

    public void ClearCache()
    {
      IList<string> cacheItems = new List<string>();
      IDictionaryEnumerator enumerator = _cache.GetEnumerator();
      while(enumerator.MoveNext())
        cacheItems.Add(enumerator.Key.ToString());

      foreach (string item in cacheItems)
        _cache.Remove(item);
    }

    public void UpdateCache<T>(IApplicationTask<T> task)
    {
      Type t = task.GetType();
      var x = _cacheDependencyList.Get
    }
  }
}